from django.shortcuts import render

import json
import os
import uuid
from datetime import datetime

from django.core.paginator import Paginator
from django.db import transaction
from django.http import JsonResponse
from django.shortcuts import render

from blueapps.account.decorators import login_exempt

from y_plan.models import Plan
from blueapps import account
from blueapps.account.models import User

# Create your views here.

def home(request):
    """
    ⾸⻚
    """
    return render(request, 'y_plan/index_home.html')

def add_plan(request):
    """
    添加计划
    """
    return render(request, 'y_plan/add_plan/index.html')


def plan_table(request):
    """
    计划图表
    """
    return render(request, 'y_plan/plan_table/index.html')

def settings(request):
    """
    设置
    """
    return render(request, 'y_plan/settings/index.html')





def save_plan_info(request):
    """
    保存计划数据
    """
    try:
        plan_name = request.POST.get('plan_name')
        requirement = request.POST.get('requirement')
        plan_grade = int(request.POST.get('plan_grade'))
        plan_type = int(request.POST.get('plan_type'))
        plan_details= request.POST.get('plan_details')
        plan_start = request.POST.get('plan_start')
        plan_end = request.POST.get('plan_end')
        if plan_start >= plan_end:
            return JsonResponse({"result": False, "code": 101, "message": "结束日期不能小于等于开始日期"}) 
        kwargs = {
            "plan_name": plan_name,
            "requirement": requirement,
            "plan_grade": plan_grade,
            "plan_start": plan_start,
            "plan_end": plan_end,
            "plan_type": plan_type,
            "plan_details": plan_details
        }
        println(提交成功)
    except Exception:
        return JsonResponse({"result": False, "code": 101, "message": "参数获取错误"})
    plan_id = request.POST.get("plan_id", None)
    if plan_id:
        # 修改
        try:
            Plan.objects.filter(id=plan_id).update(**kwargs)
        except Exception:
            return JsonResponse({"result": False, "code": 101, "message": "修改数据错误"})
    else:
        # 添加数据
        try:
            Plan.objects.create(**kwargs)
        except Exception:
            return JsonResponse({"result": False, "code": 101, "message": "保存数据错误"})
    return JsonResponse({"result": True, "code": 200, "message": "success"})


def get_plan_info_by_id(request, plan_id):
    """
    获取编辑的数据
    """
    try:
        plan_item = Plan.objects.get(id=int(plan_id))
        return JsonResponse(
            {
                "result": True, "code": 200,
                "data": {
                    "info": {
                        'data': {
                            "id": plan_item.id,
                            "plan_grade": plan_item.plan_grade,
                            "plan_name": plan_item.plan_name,
                            "requirement": plan_item.requirement,
                            "plan_start": plan_item.plan_start.strftime("%Y-%m-%d %H:%M:%S"),
                            "eplan_end": plan_item.plan_end.strftime("%Y-%m-%d %H:%M:%S"),
                            "plan_type": plan_item.plan_type,
                            "plan_details": plan_item.plan_details
                        }
                    }
                }
            }
        )
    except Exception:
        return JsonResponse({"result": False, "code": 101, "message": "获取数据失败"})

def get_plan_list(request):
    """
    获取计划列表数据
    """
    # 获取操作次数
    draw = int(request.POST.get("draw"))
    # 获取起始位置
    start = int(request.POST.get("start"))

    # 查询
    kwargs = {}
    if request.POST.get("search_plan_name", ""):
        kwargs.update({"pland_name__contains": request.POST.get("search_plan_name")})
    if request.POST.get("search_apply_time", ""):
        kwargs.update({"plan_end__gte": datetime.strptime(request.POST.get("search_apply_time"), '%Y-%m-%d')})
        kwargs.update({"plan_start__lte": datetime.strptime(request.POST.get("search_apply_time"), '%Y-%m-%d')})
    plans = Plan.objects.filter(**kwargs)
    total = len(plans)
    page_length = int(request.POST.get("length"))
    page = start / page_length + 1

    paginator = Paginator(plans, page_length)
    plans = paginator.get_page(page)
    result_data = []
    for plan_item in awards:
        result_data.append(
            {
                "id": plan_item.id,
                "plan_grade": plan_item.plan_grade,
                "plan_name": plan_item.plan_name,
                "requirement": plan_item.requirement,
                "plan_start": plan_item.plan_start.strftime("%Y-%m-%d %H:%M:%S"),
                "eplan_end": plan_item.plan_end.strftime("%Y-%m-%d %H:%M:%S"),
                "plan_type": plan_item.plan_type,
                "plan_details": plan_item.plan_details
            }
        )
    return JsonResponse(
        {
            "result": True, "code": 200,
            "data": {
                "info": {
                    'data': result_data,
                    "recordsTotal": total,
                    "recordsFiltered": total,
                    "draw": draw,
                }
            }
        }
    )

def delete_plan_info(request, plan_id):
    """
    删除数据
    """
    try:
        with transaction.atomic():
            plan_obj = Plan.objects.get(id=int(plan_id))
            plan_obj.delete()
    except Exception:
        return JsonResponse({"result": False, "code": 101, "message": "删除数据失败"})
    return JsonResponse(
        {
            "result": True, "code": 200,
            "message": "success"
        }
    )
